/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.googlecode.ivybeans.module.nodes;

import com.googlecode.ivybeans.module.FileHelper;
import com.googlecode.ivybeans.module.IvyDescriptorHelper;
import com.googlecode.ivybeans.module.IvyLibraryController;
import com.googlecode.ivybeans.module.resources.ResourcesAccess;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.netbeans.api.project.Project;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.nodes.Children;
import org.openide.nodes.FilterNode;
import org.openide.nodes.Node;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.lookup.Lookups;

/**
 * 
 * @author lforet
 */
public class IvyFilesNode extends AnnotatedAbstractNode {

    private Project project;
    private IvyLibraryController ivyLibraryController;

    public IvyFilesNode(Project project) {
        super(new IvyFilesChildren(project), Lookups.fixed(project.getProjectDirectory()));
        setName("ivyfiles"); //NOI18N
        setDisplayName(org.openide.util.NbBundle.getMessage(ResourcesAccess.class, "CTL_FilesNode"));
        this.project = project;
        ivyLibraryController = project.getLookup().lookup(IvyLibraryController.class);
        setMyFiles();
    }

    private Image getIcon(boolean opened) {
        Image badge = ImageUtilities.loadImage("com/googlecode/ivybeans/module/resources/ivyfiles-badge.png", true); //NOI18N
        Image img = ImageUtilities.mergeImages(NodeUtils.getTreeFolderIcon(opened), badge, 8, 8);
        return img;
    }

    @Override
    protected Image getIconImpl(int param) {
        return getIcon(false);
    }

    @Override
    protected Image getOpenedIconImpl(int param) {
        return getIcon(true);
    }

    @Override
    public Action[] getActions(boolean context) {
        List<Action> actions = new ArrayList<Action>();
        if (ivyLibraryController.getDescriptorFile() == null) {
            actions.add(new CreateDescriptorAction());
        }
        if (ivyLibraryController.getSettingsFile() == null) {
            actions.add(new CreateSettingsAction());
        }
//        Action[] actionArray = ;
        return actions.toArray(new Action[actions.size()]);
    }

    private void setMyFiles() {
        Set<FileObject> fobs = new HashSet<FileObject>();
        if (ivyLibraryController.getDescriptorFile() != null) {
            FileObject fo = FileUtil.toFileObject(ivyLibraryController.getDescriptorFile());
            if (fo != null) {
                fobs.add(fo);
            }
        }
        if (ivyLibraryController.getSettingsFile() != null) {
            FileObject fo2 = FileUtil.toFileObject(ivyLibraryController.getSettingsFile());
            if (fo2 != null) {
                fobs.add(fo2);
            }
        }
        setFiles(fobs);
    }

    private class CreateDescriptorAction extends AbstractAction {

        public CreateDescriptorAction() {
            putValue(Action.NAME, NbBundle.getMessage(ResourcesAccess.class, "BTN_Create_Descriptor"));
        }

        public void actionPerformed(ActionEvent event) {
            FileObject ivyFO = IvyDescriptorHelper.getInstance().createDescriptorTemplate(project);
            IvyLibraryController ilc = project.getLookup().lookup(IvyLibraryController.class);
            ilc.setDescriptorFile(FileUtil.toFile(ivyFO));
        }
    }

    private class CreateSettingsAction extends AbstractAction {

        public CreateSettingsAction() {
            putValue(Action.NAME, NbBundle.getMessage(ResourcesAccess.class, "BTN_Create_Settings"));
        }

        public void actionPerformed(ActionEvent event) {
            FileObject ivyFO = IvyDescriptorHelper.getInstance().createSettingsTemplate(project);
            IvyLibraryController ilc = project.getLookup().lookup(IvyLibraryController.class);
            ilc.setSettingsFile(FileUtil.toFile(ivyFO));
        }
    }

    private static class IvyFilesChildren extends Children.Keys<File> implements PropertyChangeListener {

        private Project project;
        private IvyLibraryController ivyLibraryController;

        public IvyFilesChildren(Project project) {
            super();
            this.project = project;
            ivyLibraryController = project.getLookup().lookup(IvyLibraryController.class);
            ivyLibraryController.addPropertyChangeListener(this);
            setKeys();
        }

        protected Node[] createNodes(File fil) {
            FileObject fo = FileUtil.toFileObject(fil);
            if (fo != null) {
                try {
                    DataObject dobj = DataObject.find(fo);
                    FilterNode node = new FilterNode(dobj.getNodeDelegate().cloneNode());
                    node.setDisplayName(FileHelper.getInstance().getPath(project.getProjectDirectory(), fil));
                    return new Node[]{node};
                } catch (DataObjectNotFoundException e) {
                    //NOPMD
                }

            }
            return new Node[0];
        }

        public void propertyChange(PropertyChangeEvent evt) {
            if (IvyLibraryController.DESCRIPTOR_CHANGE.equals(evt.getPropertyName()) || IvyLibraryController.SETTINGS_CHANGE.equals(evt.getPropertyName())) {
                setKeys();
            }
        }

        private void setKeys() {
            Collection<File> keys = new ArrayList<File>();
            if (ivyLibraryController.getDescriptorFile() != null) {
                keys.add(ivyLibraryController.getDescriptorFile());
            }
            if (ivyLibraryController.getSettingsFile() != null) {
                keys.add(ivyLibraryController.getSettingsFile());
            }
            setKeys(keys);
        }
    }
}
